import { defineStore } from 'pinia'
import { get } from '@/utils'
import type { RouteRecordNormalized, RouteRecordRaw, RouteLocationNormalizedLoaded } from 'vue-router'
import defaultSettings from '@/config/settings.json'
import { AppState } from './types'
import cloneDeep from 'lodash/cloneDeep'
import useRoutes from '@/hooks/useRoutes'
import { appRoutes } from '@/router/routes'

const useAppStore = defineStore('app', {
  state: (): AppState => ({ ...defaultSettings, imgUrl: '', pageButtons: [] }),

  getters: {
    appCurrentSetting(state: AppState): AppState {
      return { ...state }
    },
    appDevice(state: AppState) {
      return state.device
    },
    appAsyncMenus(state: AppState): RouteRecordNormalized[] {
      return state.serverMenu as unknown as RouteRecordNormalized[]
    },
    /**获取当前页面的按钮权限组 */
    getCurrentPageButton(state: AppState) {
      console.log(state.pageButtons)
      if (state.pageButtons.length) {
        const [item] = state.pageButtons.filter(f => f.code == (this.route as RouteLocationNormalizedLoaded).name)
        return item?.children || []
      }
      return []
    },
  },

  actions: {
    // Update app settings
    updateSettings(partial: Partial<AppState>) {
      // @ts-ignore-next-line
      this.$patch(partial)
    },

    // Change theme color
    toggleTheme(dark: boolean) {
      if (dark) {
        this.theme = 'dark'
        document.body.setAttribute('arco-theme', 'dark')
      } else {
        this.theme = 'light'
        document.body.removeAttribute('arco-theme')
      }
    },
    toggleDevice(device: string) {
      this.device = device
    },
    toggleMenu(value: boolean) {
      this.hideMenu = value
    },
    async fetchServerMenuConfig() {
      return new Promise((resolve, reject) => {
        get({ url: '/server-shop/sys-seller/seller/menu/routes' }, async ({ data }) => {
          const { filterRoutes, mergeArrays } = useRoutes(data)
          const result = mergeArrays(filterRoutes(cloneDeep(appRoutes)))
          this.serverMenu = result
          await this.fetchServerPageButtons()
          resolve({})
        })
      })
    },
    /**页面按钮级权限控制 */
    fetchServerPageButtons() {
      return new Promise((resolve, reject) => {
        get({ url: '/server-shop/sys-seller/seller/menu/buttons' }, ({ data }) => {
          this.pageButtons = data
          resolve({})
        })
      })
    },
    clearServerMenu() {
      this.serverMenu = []
    },
    getImgUrl() {
      get({ url: '/beforeLogin/getOssBucketNameAndEndpoint' }, ({ data }) => {
        this.imgUrl = data
      })
    },
  },
})

export default useAppStore
